package com.tjhk.demo.taos.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;

@Slf4j
public class BeanUtil {

    /*
     * Java对象转Map
     * @attention: 实体类的属性必须有对应的get()方法
     * @param: bean Java对象
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    public static Map<String, Object> fromJavaBean(Object bean) {
        if (null == bean) return null;

        try {
            Map<String, Object> map = BeanUtils.describe(bean);
            // 移除key=class
            map.remove("class");
            log.debug("JavaBean-->Map转换前：" + bean.toString());
            log.debug("JavaBean-->Map转换后：" + map);
            return map;
        } catch (Exception e) {
            log.error("JavaBean-->Map转换失败：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    /*
     * Map转java对象
     * @attention: 实体类不能使用lombok注解@Accessors(chain = true)，否则将会赋值失败
     *  实体类的属性必须有对应的set()方法
     * @param: clazz    java类
     * @param: map  待转换
     * @return: T
     */
    public static <T> T toJavaBean(Class<?> clazz, Map map) {
        try {
            T newBeanInstance = (T) clazz.newInstance();
            BeanUtils.populate(newBeanInstance, map);
            log.debug("Map-->JavaBean转换前：" + map);
            log.debug("Map-->JavaBean转换后：" + newBeanInstance.toString());
            return newBeanInstance;
        } catch (Exception e) {
            log.error("Map-->JavaBean转换失败：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
